package com.cn.qgx428.orderingmeal;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.qgx428.orderingmeal.adapter.FoodAdapter;
import com.cn.qgx428.orderingmeal.adapter.RBaseAdapter;
import com.cn.qgx428.orderingmeal.adapter.ShopAdapter;
import com.cn.qgx428.orderingmeal.myClass.CollectionFood;
import com.cn.qgx428.orderingmeal.myClass.CollectionShop;
import com.cn.qgx428.orderingmeal.myClass.Comment;
import com.cn.qgx428.orderingmeal.myClass.Food;
import com.cn.qgx428.orderingmeal.myClass.MyKeyInfo;
import com.cn.qgx428.orderingmeal.myClass.Shop;
import com.cn.qgx428.orderingmeal.myClass.User;
import com.cn.qgx428.orderingmeal.viewHolder.RViewHolder;
import com.squareup.picasso.Picasso;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class Store extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "Store";

    private MyKeyInfo keyInfo;

    private ImageView store_back;

    private TextView shop_name;
    private TextView shop_address;
    private ImageView shop_pic;
    private RatingBar ratingBar;

    private RecyclerView foodRecyler;
    private RecyclerView commentRecycler;
    private StaggeredGridLayoutManager layoutManager;
    private FoodAdapter foodAdapter;

    private int dataAmount = 4; //每次返回的数据
    private int dataAllready = 4; //已返回的数据
    private int lastVisableItem;

    private static final int COLLECTION_SHOP = 1;
    private static final int NOT_COLLECTION_SHOP = 0;
    private int collectShop = NOT_COLLECTION_SHOP;

    private String collectionDataID; //存储店铺收藏ID
    private LinearLayout collectionBtnLayout;
    private ImageView collectionImg;
    private LinearLayout phone;
    private LinearLayout store_comment;
    private ImageView commentImg;
    
    private static final int FOOD_VIEW = 0;
    private static final int COMMENT_VIEW =1;
    private int NOW_VIEW = FOOD_VIEW;

    Boolean isGetComment = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store);

        Bmob.initialize(this, "1b925fe2ccbb402f4034a3e28c31ad93");
        init();
        getFirstData();
    }

    private void getFirstData() {
        //查询属于该店铺的食物
        BmobQuery<Food> query = new BmobQuery<Food>();
        Shop shop = new Shop();
        shop.setObjectId(keyInfo.getNowShopID());
        Log.d(TAG, "getFoodData: " + keyInfo.getNowShopID());
        query.addWhereEqualTo("shop", new BmobPointer(shop));
        query.findObjects(new FindListener<Food>() {
            @Override
            public void done(List<Food> list, BmobException e) {
                if (e == null) {
                    Log.d(TAG, "done: " + list.size());
                    foodAdapter = new FoodAdapter(Store.this, list, keyInfo, Store.this);
                    foodRecyler.setAdapter(foodAdapter);
                } else {
                    Toast.makeText(Store.this, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "done: " + e.getErrorCode() + e.getMessage());
                }
            }
        });

        //根据数据表更新店铺按钮
        BmobQuery<CollectionShop> eq1 = new BmobQuery<CollectionShop>();
        Shop sqlShop = new Shop();
        sqlShop.setObjectId(keyInfo.getNowShopID());
        eq1.addWhereEqualTo("shop", sqlShop);
        BmobQuery<CollectionShop> eq2 = new BmobQuery<CollectionShop>();
        User sqlUser = new User();
        sqlUser.setObjectId(keyInfo.getUserID());
        eq2.addWhereEqualTo("user", sqlUser);
        List<BmobQuery<CollectionShop>> andQuerys = new ArrayList<BmobQuery<CollectionShop>>();
        andQuerys.add(eq1);
        andQuerys.add(eq2);
        BmobQuery<CollectionShop> queryAnd = new BmobQuery<CollectionShop>();
        queryAnd.and(andQuerys);
        queryAnd.findObjects(new FindListener<CollectionShop>() {
            @Override
            public void done(List<CollectionShop> list, BmobException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        //提取数据ID
                        collectionDataID = list.get(0).getObjectId();
                        collectionImg.setImageResource(R.drawable.store_collection1);
                        collectShop = COLLECTION_SHOP;
                    }
                } else {
                    Toast.makeText(Store.this, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "搜查收藏表: " + e.getErrorCode() + e.getMessage());
                }
            }
        });

    }

    private void init() {
        keyInfo = (MyKeyInfo) getIntent().getSerializableExtra("keyInfo");
        shop_name = (TextView) findViewById(R.id.store_name);
        shop_address = (TextView) findViewById(R.id.store_address);
        shop_pic = (ImageView) findViewById(R.id.store_pic);
        shop_name.setText(keyInfo.getNowShopName());
        shop_address.setText(keyInfo.getNowShopAddress());
        Picasso.with(this).load(keyInfo.getNowPicUrl()).fit().into(shop_pic);
        ratingBar = (RatingBar) findViewById(R.id.sotre_grade);
        ratingBar.setRating(keyInfo.getShopGrade());

        store_back = (ImageView) findViewById(R.id.store_back);
        store_back.setOnClickListener(this);

        foodRecyler = (RecyclerView) findViewById(R.id.store_food_recycler);
        layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        foodRecyler.setLayoutManager(layoutManager);
        commentRecycler = (RecyclerView) findViewById(R.id.store_comment_recycler);
        commentRecycler.setLayoutManager(new LinearLayoutManager(this));

        collectionBtnLayout = (LinearLayout) findViewById(R.id.store_collection);
        collectionImg = (ImageView) findViewById(R.id.store_collection_img);
        collectionBtnLayout.setOnClickListener(this);
        phone = (LinearLayout) findViewById(R.id.store_phoneLayout);
        phone.setOnClickListener(this);
        store_comment = (LinearLayout) findViewById(R.id.store_comment);
        store_comment.setOnClickListener(this);
        commentImg = (ImageView) findViewById(R.id.store_comment_img);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.store_back:
                finish();
                break;
            case R.id.store_collection:
                changeCollectionShop();
                break;
            case R.id.store_phoneLayout:
                callToPhone();
                break;
            case R.id.store_comment:
                changeRecyclerView(NOW_VIEW);
        }
    }

    private void changeRecyclerView(int now_view) {
        if (now_view == FOOD_VIEW){
            foodRecyler.setVisibility(View.GONE);
            commentImg.setImageResource(R.drawable.order_dishe_white);
            commentRecycler.setVisibility(View.VISIBLE);
            NOW_VIEW = COMMENT_VIEW;
            if (isGetComment == false){
                getCommentData();
            }
        } else if(now_view == COMMENT_VIEW){
            commentRecycler.setVisibility(View.GONE);
            commentImg.setImageResource(R.drawable.store_comment);
            foodRecyler.setVisibility(View.VISIBLE);
            NOW_VIEW = FOOD_VIEW;
        }
    }

    private void getCommentData() {
        BmobQuery<Comment> query = new BmobQuery<Comment>();
        Shop shop = new Shop ();
        shop.setObjectId(keyInfo.getNowShopID());
        query.addWhereEqualTo("shop",new BmobPointer(shop));
        query.include("user");
        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (e==null){
                    setCommentRecyclerView(list);
                    for (Comment c : list){
                        Log.d(TAG, "done: 评论信息 "+c.getUser().getName()+" "+c.getContent());
                    }
                }else {
                    Toast.makeText(Store.this, "服务器错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "done: 获取评论失败 "+e.getErrorCode()+e.getMessage());
                }
            }
        });
    }

    private void setCommentRecyclerView(List<Comment> list) {
        commentRecycler.setAdapter(new RBaseAdapter(this,list,R.layout.store_comment_item_view) {
            @Override
            public void convert(RViewHolder holder, Object item) {
                Comment comment = (Comment)item;
                User user = comment.getUser();
                TextView userName = holder.getView(R.id.store_comment_item_userName);
                TextView time = holder.getView(R.id.store_comment_item_time);
                TextView content = holder.getView(R.id.store_comment_item_comment);

                userName.setText(user.getName());
                time.setText(comment.getCreatedAt());
                content.setText(comment.getContent());
            }
        });
    }

    private void callToPhone() {
        /**
         *  借助ContextCompat.checkSelfPermission()方法判断是否授予权限，接收两个参数，Context和具体权限名，方法的返回值与
         *  PackageManager.PERMISSION_GRANTED做比较，相等说明已经授权
         */
        if(ContextCompat.checkSelfPermission(Store.this,Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            /**
             * 同样借助ContextCompat.requestPermissions()方法弹出权限申请的对话框
             * 参数为Context,具体权限名，作为返回结果的识别码（自定义）
             */
            ActivityCompat.requestPermissions(Store.this,new String[]{Manifest.permission.CALL_PHONE},1);
        }else{
            //已授权拨打电话
            try{
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:"+keyInfo.getShopPhone()));
                startActivity(intent);
            } catch (SecurityException e){
                e.printStackTrace();
            }
        }
    }


        /**
         * @param requestCode 前面定义的反馈结果识别码
         * @param permissions
         * @param grantResults 授权结果
         */
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode){
                case 1:
                    //授权重新调用callToPhone
                    if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                        callToPhone();
                    } else {
                        //不授权提示用户的操作
                        Toast.makeText(this, "您拒绝授权", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
            }
        }

    private void changeCollectionShop() {
        CollectionShop collectionShop = new CollectionShop();
        Shop shop = new Shop();
        shop.setObjectId(keyInfo.getNowShopID());
        User user = new User();
        user.setObjectId(keyInfo.getUserID());
        collectionShop.setShop(shop);
        collectionShop.setUser(user);
        if (collectShop == NOT_COLLECTION_SHOP){
            collectionShop.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null){
                        collectionImg.setImageResource(R.drawable.store_collection1);
                        collectShop = COLLECTION_SHOP;
                        collectionDataID = s;
                        Toast.makeText(Store.this, "收藏店铺", Toast.LENGTH_SHORT).show();
                    } else{
                        Toast.makeText(Store.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "done: "+e.getErrorCode()+e.getMessage());
                    }
                }
            });
        } else if(collectShop == COLLECTION_SHOP){
            collectionShop.setObjectId(collectionDataID);
            collectionShop.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null){
                        collectionImg.setImageResource(R.drawable.store_collection);
                        collectShop = NOT_COLLECTION_SHOP;
                        Toast.makeText(Store.this, "取消收藏店铺", Toast.LENGTH_SHORT).show();
                    } else{
                        Toast.makeText(Store.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "done: "+e.getErrorCode()+e.getMessage());
                    }
                }
            });
        }
    }
}
